import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class MemberService extends BaseService<any> {
  private readonly logger = new Logger(MemberService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * add
   * 对应 PHP: MemberService_api::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $data['site_id'] = $this->site_id;         return $this->model->create($data)?->member_id ?? 0;     }      /**      * 更新会员      * @param array $data  ...
data.site_id = this.site_id;
        return this.model.create(data)?.member_id || 0;
    }

    /**
     * 更新会员
     * @param data
     * @return true
     */
    async edit(data)
    {
        const member = this.findMemberInfo([member_id: this.member_id, site_id: this.site_id)];

        if(member.isEmpty()) throw new ApiBusinessException('MEMBER_NOT_EXIST');
        member.allowField(['nickname', 'headimg', 'birthday', 'sex', 'last_visit_time')).save(data);
        return true;
    }

    /**
     * 获取会员信息
     * @return */
    async getInfo()
    {
        const field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, balance, growth, is_member, member_time, is_del, province_id, city_id, district_id, address, location, money, money_get, wx_openid, weapp_openid, commission, commission_get, commission_cash_outing';
        const member_info = this.model.where([['member_id', '=', this.member_id))).with(.member_level_name_bind).field(field).append(.sex_name).findOrEmpty().toArray(];
        if (!!member_info)) {
            const config = this.coreMemberConfigService.getMemberConfig(this.site_id);
            member_info.form_id = config.form_id;
            member_info.form_record_id = '';
            if (!!member_info.form_id)) {
                const diy_form_records_model = this.diyFormRecordsService;
                const form_records = diy_form_records_model.field('record_id').where([['form_id', '=', member_info.form_id], ['member_id', '=', member_info.member_id))).order('create_time desc').findOrEmpty().toArray(];
                if (!!form_records)) {
                    member_info.form_record_id = form_records.record_id;
                }
            }
  }

  /**
   * edit
   * 对应 PHP: MemberService_api::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $member = $this->findMemberInfo(['member_id' => $this->member_id, 'site_id' => $this->site_id]);          if($member->isEmpty()) throw new ApiExceptio...
const member = this.findMemberInfo([member_id: this.member_id, site_id: this.site_id)];

        if(member.isEmpty()) throw new ApiBusinessException('MEMBER_NOT_EXIST');
        member.allowField(['nickname', 'headimg', 'birthday', 'sex', 'last_visit_time')).save(data);
        return true;
    }

    /**
     * 获取会员信息
     * @return */
    async getInfo()
    {
        const field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, balance, growth, is_member, member_time, is_del, province_id, city_id, district_id, address, location, money, money_get, wx_openid, weapp_openid, commission, commission_get, commission_cash_outing';
        const member_info = this.model.where([['member_id', '=', this.member_id))).with(.member_level_name_bind).field(field).append(.sex_name).findOrEmpty().toArray(];
        if (!!member_info)) {
            const config = this.coreMemberConfigService.getMemberConfig(this.site_id);
            member_info.form_id = config.form_id;
            member_info.form_record_id = '';
            if (!!member_info.form_id)) {
                const diy_form_records_model = this.diyFormRecordsService;
                const form_records = diy_form_records_model.field('record_id').where([['form_id', '=', member_info.form_id], ['member_id', '=', member_info.member_id))).order('create_time desc').findOrEmpty().toArray(];
                if (!!form_records)) {
                    member_info.form_record_id = form_records.record_id;
                }
            }
  }

  /**
   * getInfo
   * 对应 PHP: MemberService_api::getInfo()
   * 逻辑类型: undefined - undefined
   */
  async getInfo() {
    // 基于PHP真实逻辑: getInfo
    // PHP原文: $field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, logi...
const field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, balance, growth, is_member, member_time, is_del, province_id, city_id, district_id, address, location, money, money_get, wx_openid, weapp_openid, commission, commission_get, commission_cash_outing';
        const member_info = this.model.where([['member_id', '=', this.member_id))).with(.member_level_name_bind).field(field).append(.sex_name).findOrEmpty().toArray(];
        if (!!member_info)) {
            const config = this.coreMemberConfigService.getMemberConfig(this.site_id);
            member_info.form_id = config.form_id;
            member_info.form_record_id = '';
            if (!!member_info.form_id)) {
                const diy_form_records_model = this.diyFormRecordsService;
                const form_records = diy_form_records_model.field('record_id').where([['form_id', '=', member_info.form_id], ['member_id', '=', member_info.member_id))).order('create_time desc').findOrEmpty().toArray(];
                if (!!form_records)) {
                    member_info.form_record_id = form_records.record_id;
                }
            }
  }

  /**
   * getCount
   * 对应 PHP: MemberService_api::getCount()
   * 逻辑类型: undefined - undefined
   */
  async getCount(condition: any) {
    // 基于PHP真实逻辑: getCount
    // PHP原文: return $this->model->where($condition)->count();     }      /**      * 会员中心信息      */     public function center()     {         $field = 'member_id, ...
return this.model.where(condition).count(];
    }

    /**
     * 会员中心信息
     */
    async center()
    {
        const field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, balance, growth, is_member, member_time, is_del, province_id, city_id, district_id, address, location, money, money_get, commission, commission_get, commission_cash_outing';
        return this.model.where([['member_id', '=', this.member_id))).field(field).append(.sex_name).findOrEmpty().toArray(];
    }

    /**
     * 获取会员的模型对象(todo  慎用!!!  现主要用于登录)
     * @param data
     * @return Member|array|mixed|Model  !!! 仔细看,返回值是模型对象  如果想要判断是否为空  请用 member.isEmpty()
     */
    async findMemberInfo(data){
        //会员账号
        if(!!data.username))
            where[] = ['username', '=', data.username];
        //会员手机号
        if(!!data.mobile))
            where[] = ['mobile', '=', data.mobile];
        //会员id
        if(!!data.member_id))
            where[] = ['member_id', '=', data.member_id];
        //微信公众号openid
        if(!!data.wx_openid))
            where[] = ['wx_openid', '=', data.wx_openid];
        //微信小程序openid
        if(!!data.weapp_openid))
            where[] = ['weapp_openid', '=', data.weapp_openid];
        // 微信unionid
        if(!!data.wx_unionid))
            where[] = ['wx_unionid', '=', data.wx_unionid];
        if(!!data.username|mobile))
            where[] = ['username|mobile', '=', data.username|mobile];
        if(!where)){
            where[] = ['member_id', '=', -1];
  }

  /**
   * center
   * 对应 PHP: MemberService_api::center()
   * 逻辑类型: undefined - undefined
   */
  async center() {
    // 基于PHP真实逻辑: center
    // PHP原文: $field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, logi...
const field = 'member_id, site_id, username, member_no, mobile, register_channel, nickname, headimg, member_level, member_label, login_ip, login_type, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, balance, growth, is_member, member_time, is_del, province_id, city_id, district_id, address, location, money, money_get, commission, commission_get, commission_cash_outing';
        return this.model.where([['member_id', '=', this.member_id))).field(field).append(.sex_name).findOrEmpty().toArray(];
    }

    /**
     * 获取会员的模型对象(todo  慎用!!!  现主要用于登录)
     * @param data
     * @return Member|array|mixed|Model  !!! 仔细看,返回值是模型对象  如果想要判断是否为空  请用 member.isEmpty()
     */
    async findMemberInfo(data){
        //会员账号
        if(!!data.username))
            where[] = ['username', '=', data.username];
        //会员手机号
        if(!!data.mobile))
            where[] = ['mobile', '=', data.mobile];
        //会员id
        if(!!data.member_id))
            where[] = ['member_id', '=', data.member_id];
        //微信公众号openid
        if(!!data.wx_openid))
            where[] = ['wx_openid', '=', data.wx_openid];
        //微信小程序openid
        if(!!data.weapp_openid))
            where[] = ['weapp_openid', '=', data.weapp_openid];
        // 微信unionid
        if(!!data.wx_unionid))
            where[] = ['wx_unionid', '=', data.wx_unionid];
        if(!!data.username|mobile))
            where[] = ['username|mobile', '=', data.username|mobile];
        if(!where)){
            where[] = ['member_id', '=', -1];
  }

  /**
   * findMemberInfo
   * 对应 PHP: MemberService_api::findMemberInfo()
   * 逻辑类型: undefined - undefined
   */
  async findMemberInfo(data: any[]) {
    // 基于PHP真实逻辑: findMemberInfo
    // PHP原文: //会员账号         if(!empty($data['username']))             $where[] = ['username', '=', $data['username']];         //会员手机号         if(!empty($data['mob...
//会员账号
        if(!!data.username))
            where[] = ['username', '=', data.username];
        //会员手机号
        if(!!data.mobile))
            where[] = ['mobile', '=', data.mobile];
        //会员id
        if(!!data.member_id))
            where[] = ['member_id', '=', data.member_id];
        //微信公众号openid
        if(!!data.wx_openid))
            where[] = ['wx_openid', '=', data.wx_openid];
        //微信小程序openid
        if(!!data.weapp_openid))
            where[] = ['weapp_openid', '=', data.weapp_openid];
        // 微信unionid
        if(!!data.wx_unionid))
            where[] = ['wx_unionid', '=', data.wx_unionid];
        if(!!data.username|mobile))
            where[] = ['username|mobile', '=', data.username|mobile];
        if(!where)){
            where[] = ['member_id', '=', -1];
  }

  /**
   * editByFind
   * 对应 PHP: MemberService_api::editByFind()
   * 逻辑类型: undefined - undefined
   */
  async editByFind(member: any, data: any) {
    // 基于PHP真实逻辑: editByFind
    // PHP原文: return $member->save($data);     }      /**      * 修改字段      * @param string $field      * @param $data      * @return null      */     public functio...
return member.save(data);
    }

    /**
     * 修改字段
     * @param string field
     * @param data
     * @return null
     */
    async modify(string field, data)
    {
        return this.coreMemberService.modify(this.site_id, this.member_id, field, data);
    }

    async getQrcode(){
        // 生成会员二维码
        const qrcode_dir = 'upload/member/temp';
        if (!is_dir(qrcode_dir)) mkdir(qrcode_dir, intval('0755', 8), true];
        const id = "member-".this.member_id;
        const qrcode_path = "{qrcode_dir}/order_qrcode_{this.member_id}.png";
        \core\util\QRcode.png(id, qrcode_path, 'L', 16, 1);

        // 生成会员条形码
        const barcode_path = (new Barcode(14, id)).generateBarcode(qrcode_dir, 2];
        const detail = [];
        detail.verify_code_qrcode = image_to_base64(qrcode_path, true];
        detail.verify_code_barcode = image_to_base64(barcode_path);
        return detail;
    }

    /**
     * 初始化会员数据
     */
    async initMemberData(){
        if (this.member_id) {
            event("MemberLoginAfter", [site_id: this.site_id, member_id: this.member_id)];
  }

  /**
   * modify
   * 对应 PHP: MemberService_api::modify()
   * 逻辑类型: undefined - undefined
   */
  async modify(field: string, data: string) {
    // 基于PHP真实逻辑: modify
    // PHP原文: return (new CoreMemberService())->modify($this->site_id, $this->member_id, $field, $data);     }      public function getQrcode(){         // 生成会员二维码 ...
return this.coreMemberService.modify(this.site_id, this.member_id, field, data);
    }

    async getQrcode(){
        // 生成会员二维码
        const qrcode_dir = 'upload/member/temp';
        if (!is_dir(qrcode_dir)) mkdir(qrcode_dir, intval('0755', 8), true];
        const id = "member-".this.member_id;
        const qrcode_path = "{qrcode_dir}/order_qrcode_{this.member_id}.png";
        \core\util\QRcode.png(id, qrcode_path, 'L', 16, 1);

        // 生成会员条形码
        const barcode_path = (new Barcode(14, id)).generateBarcode(qrcode_dir, 2];
        const detail = [];
        detail.verify_code_qrcode = image_to_base64(qrcode_path, true];
        detail.verify_code_barcode = image_to_base64(barcode_path);
        return detail;
    }

    /**
     * 初始化会员数据
     */
    async initMemberData(){
        if (this.member_id) {
            event("MemberLoginAfter", [site_id: this.site_id, member_id: this.member_id)];
  }

  /**
   * getQrcode
   * 对应 PHP: MemberService_api::getQrcode()
   * 逻辑类型: undefined - undefined
   */
  async getQrcode() {
    // 基于PHP真实逻辑: getQrcode
    // PHP原文: // 生成会员二维码         $qrcode_dir = 'upload/member/temp';         if (!is_dir($qrcode_dir)) mkdir($qrcode_dir, intval('0755', 8), true);         $id = "m...
// 生成会员二维码
        const qrcode_dir = 'upload/member/temp';
        if (!is_dir(qrcode_dir)) mkdir(qrcode_dir, intval('0755', 8), true];
        const id = "member-".this.member_id;
        const qrcode_path = "{qrcode_dir}/order_qrcode_{this.member_id}.png";
        \core\util\QRcode.png(id, qrcode_path, 'L', 16, 1);

        // 生成会员条形码
        const barcode_path = (new Barcode(14, id)).generateBarcode(qrcode_dir, 2];
        const detail = [];
        detail.verify_code_qrcode = image_to_base64(qrcode_path, true];
        detail.verify_code_barcode = image_to_base64(barcode_path);
        return detail;
    }

    /**
     * 初始化会员数据
     */
    async initMemberData(){
        if (this.member_id) {
            event("MemberLoginAfter", [site_id: this.site_id, member_id: this.member_id)];
  }

  /**
   * initMemberData
   * 对应 PHP: MemberService_api::initMemberData()
   * 逻辑类型: undefined - undefined
   */
  async initMemberData() {
    // 基于PHP真实逻辑: initMemberData
    // PHP原文: if ($this->member_id) {             event("MemberLoginAfter", ['site_id' => $this->site_id, 'member_id' => $this->member_id]);...
if (this.member_id) {
            event("MemberLoginAfter", [site_id: this.site_id, member_id: this.member_id)];
  }
}
